/*
 * Copyright (c) 2020-2021 imlzw@vip.qq.com jweb.cc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package cc.jweb.adai.web.system.generator.service.dataprocess.impl;

import cc.jweb.adai.web.system.generator.model.vo.ConfigElement;
import cc.jweb.adai.web.system.generator.service.dataprocess.DataProcess;
import cc.jweb.adai.web.system.generator.model.vo.Config;

import java.util.ArrayList;
import java.util.List;



/**
 * 字符串正则替换
 *
 * @author 志伟
 *
 */
public class StringRegexReplace implements DataProcess {

	//正则表达式
	public static String MATCH_REGEX = "srr_matchRegex";
	//替换内容表达式
	public static String REPLACEMENT = "srr_replecement";
	//配置元素列表
	private List<ConfigElement> configElementList = null;

	public StringRegexReplace(){
		configElementList = new ArrayList<ConfigElement>();
		configElementList.add(new ConfigElement("匹配正则表达式",MATCH_REGEX,null,true,false));
		configElementList.add(new ConfigElement("替换内容表达式",REPLACEMENT,null,true,false));
	}

	@SuppressWarnings("unchecked")
	@Override
	public String process(Object object, Config config)  throws Exception{
		String replacedString = null;
		if(object!=null){
			String string = object.toString();
			replacedString = string;
			if(string!=null&&string.trim().length()>0){
				String matchRegex = config!=null?config.getConfig(MATCH_REGEX):null;
				String replacement = config!=null?config.getConfig(REPLACEMENT):null;
				if(matchRegex!=null&&matchRegex.trim().length()>0&&replacement!=null){
					replacedString = string.replaceAll(matchRegex, replacement);
				}
			}
		}
		return replacedString;
	}


	@Override
	public String getConfigDesc() {
		return "/*字符串正则替换，正则配置：{"+MATCH_REGEX+":\"\\S\"//正则表达式}*/";
	}

	@Override
	public List<ConfigElement> getConfigParams() {
		return configElementList;
	}

	public static void main(String[] args) {
		Config config = new Config();
		config.addConfig(new ConfigElement("", MATCH_REGEX, ".*(a).*"));
		config.addConfig(new ConfigElement("", REPLACEMENT, "tt$1tt"));
		try {
			String process = new StringRegexReplace().process("abcdef", config );
			System.out.println(process);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
